package com.libra.assemble.web.listener.jms;

import com.google.common.collect.Maps;
import com.libra.assemble.xutil.email.AttachmentForm;
import com.libra.assemble.xutil.enums.MessageType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.Destination;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * JMS用户变更消息生产者.
 * <p/>
 * 使用jmsTemplate将用户变更消息分别发送到queue与topic.
 */
public class NotifyMessageProducer {

    private static Logger logger = LoggerFactory.getLogger(NotifyMessageProducer.class);

    private JmsTemplate jmsTemplate;
    private Destination notifyQueue;
    private Destination notifyTopic;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setNotifyQueue(Destination notifyQueue) {
        this.notifyQueue = notifyQueue;
    }

    public void setNotifyTopic(Destination nodifyTopic) {
        this.notifyTopic = nodifyTopic;
    }

    /**
     * 加入队列.
     *
     * @param event  事件
     * @param openid 公众号的用户唯一标识
     */
    public void sendQueue(String event, String openid) {
        logger.info("Queue 消息处理");
        sendMessage(event, openid, notifyQueue);
    }

    /**
     * 将保存邮件附件信息加入队列.
     * @param messageType 消息类型
     * @param lineList 附件
     */
    public void sendQueue(MessageType messageType, List<String> lineList) {
        logger.info("Queue 消息处理[保存邮件附件信息]");
        Map<String, Object> map = Maps.newHashMap();
        map.put("messageType", messageType.toString());
        map.put("attachmentList", lineList);
        sendMessage(map,notifyQueue);
    }

    /**
     * 以一般规则加入JMS消息列表(一般使用队列).
     *
     * @param event  事件
     * @param openid 公众号的用户唯一标识
     */
    public void sendTopic(String event, String openid) {
        sendMessage(event, openid, notifyTopic);
    }

    /**
     * 使用jmsTemplate最简便的封装convertAndSend()发送Map类型的消息.
     *
     * @param event
     * @param openid
     * @param destination
     */
    private void sendMessage(String event, String openid, Destination destination) {
        logger.info("发送消息:{}",destination.toString());
        Map<String, Object> map = Maps.newHashMap();
        map.put("event", event);
        map.put("openid", openid);
        jmsTemplate.convertAndSend(destination, map);
    }


    /**
     * 使用jmsTemplate最简便的封装convertAndSend()发送Map类型的消息.
     *
     * @param content
     * @param destination
     */
    private void sendMessage(Map<String,Object> content, Destination destination) {
        logger.info("发送消息:{}",destination.toString());
        jmsTemplate.convertAndSend(destination, content);
    }

}
